package com.annchain.og_browser.service.impl;

import com.annchain.og_browser.service.IpService;
import com.annchain.og_browser.util.IPUtils;
import com.maxmind.geoip2.DatabaseReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

@Service
public class IpServiceImpl implements IpService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${GeoLite2City.path}")
    String filepath;

    @Override
    public String[] getLocation(String ip) {
        File database = null;
        DatabaseReader reader = null;
        // 创建 GeoLite2 数据库
        try {
            database=ResourceUtils.getFile(filepath);
        } catch (FileNotFoundException e) {
            logger.error("创建 GeoLite2 数据库出错",e);
        }
        // 读取数据库内容
        try {
            reader = new DatabaseReader.Builder(database).build();
        } catch (IOException e) {
            logger.error("读取数据库出错",e);
        }
        String[] res = new String[3];
        try {
            if(reader != null){
                res[0] = Double.toString(IPUtils.getLongitude(reader, ip));
                res[1] = Double.toString(IPUtils.getLatitude(reader, ip));
                String city = IPUtils.getCity(reader, ip);
                if(city ==null){
                    city = IPUtils.getProvince(reader,ip);
                    if(city == null) city = IPUtils.getCountry(reader,ip);
                }
                res[2] = city;
            }
        } catch (Exception e) {
            logger.error("获取城市信息出错",e);
        }
        return res;
    }
}
